package org.odk.aggregate.servlet;

import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.odk.aggregate.constants.ServletConsts;
import org.odk.aggregate.personfindermobile.FormSubmissionQueue;
import org.odk.aggregate.personfindermobile.RecordSubmitter;

import com.google.appengine.api.datastore.Entity;

/**
 * Servlet that retrieves form submissions stored in the database, process them
 * and uploads them to the Google person finder app at
 * http://haiticrisis.appspot.com/.
 * 
 * @author Marc Stogaitis
 */
public class PersonFinderUploadServlet extends ServletUtilBase {

  /**
   * URI from base
   */
  public static final String ADDR = "personFinderUpload";
  
  /**
   * Name of the form for which we should fetch the form submissions. This
   * parameter is required.
   */
  private static final String FORM_NAME_PARAM = "formname";

  /**
   * An optional parameter that sets the number of items that should be be
   * uploaded in one request. The default is 1.
   */
  private static final String UPLOAD_COUNT_PARAM = "uploadcount";

  private static final int DEFAULT_UPLOADS_PER_REQUEST = 1;

  private static final Logger logger = Logger
      .getLogger(PersonFinderUploadServlet.class.getCanonicalName());

  /**
   * Serial number for serialization
   */
  private static final long serialVersionUID = 1L;

  private final FormSubmissionQueue submissionQueue = new FormSubmissionQueue();

  @Override
  public void doGet(HttpServletRequest req, HttpServletResponse resp)
      throws IOException {
    resp.setContentType(ServletConsts.RESP_TYPE_PLAIN);

    String formName = req.getParameter(FORM_NAME_PARAM);
    if (formName == null || formName.isEmpty()) {

      resp.getWriter().println("Required parameter formname is missing.");
      return;
    }

    String uploadCountParam = req.getParameter(UPLOAD_COUNT_PARAM);
    int uploadCount = DEFAULT_UPLOADS_PER_REQUEST;
    if (uploadCountParam != null && !uploadCountParam.isEmpty()) {
      try {
        uploadCount = Integer.parseInt(uploadCountParam);
      } catch (NumberFormatException e) {
        logger.log(Level.WARNING, e.getMessage(), e);
        resp.getWriter().println("Invalid value for parameter uploadcount");
        return;
      }
    }

    for (int i = 0; i < uploadCount; i++) {
      Entity formSubmission = submissionQueue.getHead(formName);
      if (formSubmission == null) {
        break;
      }

      logger.info("Submitting the following record to Person Finder: " + formSubmission);
      String result = new RecordSubmitter().submit(formSubmission);
      resp.getWriter().println("Output: " + result);
      if (true) { // TODO(mstogaitis): placeholder where we need to call the submit to PersonFinder code.
        // Only delete the data from the queue if the upload to Google person
        // finder succeeded.
        // submissionQueue.deleteFromQueue(formSubmission);

      }
    }
    resp.getWriter().println("Success");
  }
}
